package com.cheyunkeji.er.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.utils.PhoneUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class CreateNewOrganizeActivity extends BaseActivity implements OssService.onImageProcessedResultListener, ImageSelectDialog.ImageSelectListener ,EasyPermissions.PermissionCallbacks{


    private static final int REQUEST_CODE_SELECT_PROVINCE = 10;
    private static final int REQUEST_CODE_SELECT_CITY = 2;
    private static final int REQUEST_CODE_SELECT_COUNTY = 3;
    private static final int REQUEST_CODE_SELECT_CAR_BRAND = 4;
    private static final int REQUEST_CODE_SELECT_SHOP_PROPERTY = 5;

    private static final String TAG = CreateNewOrganizeActivity.class.getSimpleName();
    private static final int REQUEST_CAMERA_FILES_PERMISSIONS = 0X1010;

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.et_company_full_name)
    EditText etCompanyFullName;
    @BindView(R.id.et_company_short_name)
    EditText etCompanyShortName;
    @BindView(R.id.tv_province)
    TextView tvProvince;
    @BindView(R.id.iv_province_select)
    ImageView ivProvinceSelect;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.iv_city_select)
    ImageView ivCitySelect;
    @BindView(R.id.tv_zone_select)
    TextView tvZoneSelect;
    @BindView(R.id.iv_zone_select)
    ImageView ivZoneSelect;
    @BindView(R.id.et_contacts)
    EditText etContacts;
    @BindView(R.id.et_contact_number)
    EditText etContactNumber;
    @BindView(R.id.tv_car_brand)
    TextView tvCarBrand;
    @BindView(R.id.iv_carbrand_select)
    ImageView ivCarbrandSelect;
    @BindView(R.id.tv_sj_xz)
    TextView tvSjXz;
    @BindView(R.id.iv_sjxz_select)
    ImageView ivSjxzSelect;
    @BindView(R.id.cb_yw_mk)
    CheckBox cbYwMk;
    @BindView(R.id.cb_jk_mk)
    CheckBox cbJkMk;
    @BindView(R.id.cb_cs_mk)
    CheckBox cbCsMk;
    @BindView(R.id.cb_fast_evaluate)
    CheckBox cbFastEvaluate;
    @BindView(R.id.et_recommend_code)
    EditText etRecommendCode;
    @BindView(R.id.et_business_license_code)
    EditText etBusinessLicenseCode;
    @BindView(R.id.iv_business_license_photo_select)
    ImageView ivBusinessLicensePhotoSelect;
    @BindView(R.id.iv_goto_top)
    ImageView ivGotoTop;
    @BindView(R.id.btn_require_submit)
    Button btnRequireSubmit;
    @BindView(R.id.activity_create_new_organize)
    LinearLayout activityCreateNewOrganize;
    @BindView(R.id.sv_content)
    ScrollView svContent;
    @BindView(R.id.iv_business_license)
    ImageView ivBusinessLicense;
    @BindView(R.id.ll_select_province)
    LinearLayout llSelectProvince;
    @BindView(R.id.ll_city_select)
    LinearLayout llCitySelect;
    @BindView(R.id.ll_zone_select)
    LinearLayout llZoneSelect;
    @BindView(R.id.ll_car_brand_select)
    LinearLayout llCarBrandSelect;
    @BindView(R.id.ll_sjxz_select)
    LinearLayout llSjxzSelect;
    @BindView(R.id.et_car_dealer_code)
    EditText etCarDealerCode;
    @BindView(R.id.et_address)
    EditText etAddress;

    private CarInfo.CarSourceCity selectedProvince, selectedCity, selectedCounty;

    //    商家性质选项下标
    private int shopPropertyIndex = 0;
    //    商家性质名称
    private String shopPropertyName = "";
    private CarInfo.CarBrand selectedCarBrand;
    private String localImgPath;

    private ImageSelectDialog imgSelectDialog ;
    private ImageCaptureManager captureManager ;

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_create_new_organize);
        ButterKnife.bind(this);
        captureManager = new ImageCaptureManager(this);
    }

    @Override
    protected void initView() {

        vTopbar.setTitle("创建新组织");
        vTopbar.setLeftBack();
        llSelectProvince.setOnClickListener(this);
        llCitySelect.setOnClickListener(this);
        llZoneSelect.setOnClickListener(this);
        llCarBrandSelect.setOnClickListener(this);
        llSjxzSelect.setOnClickListener(this);
        ivBusinessLicensePhotoSelect.setOnClickListener(this);
        ivGotoTop.setOnClickListener(this);
        btnRequireSubmit.setOnClickListener(this);

        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName())) {
            etContacts.setText(UserInfoManager.getInstance(MyApplication.getInstance()).getRealName());
        }
        if (!TextUtils.isEmpty(UserInfoManager.getInstance(MyApplication.getInstance()).getMobile())) {
            etContactNumber.setText(UserInfoManager.getInstance(MyApplication.getInstance()).getMobile());
        }
    }

    @Override
    protected void initData() {

    }

    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {

            case PhotoPicker.REQUEST_CODE:
                if (data != null) {
                    localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    ImageLoadUtil.loadImg(CreateNewOrganizeActivity.this, localImgPath, ivBusinessLicense);
                }
                break;

            case REQUEST_CODE_SELECT_PROVINCE:

                selectedProvince = (CarInfo.CarSourceCity) data.getSerializableExtra("data");
                if (null != selectedProvince) {
                    tvProvince.setText(selectedProvince.getName());
                }
                break;

            case REQUEST_CODE_SELECT_CITY:
                selectedCity = (CarInfo.CarSourceCity) data.getSerializableExtra("data");
                if (null != selectedCity) {
                    tvCity.setText(selectedCity.getName());
                }
                break;

            case REQUEST_CODE_SELECT_COUNTY:
                selectedCounty = (CarInfo.CarSourceCity) data.getSerializableExtra("data");
                if (null != selectedCounty) {
                    tvZoneSelect.setText(selectedCounty.getName());
                }
                break;

            case REQUEST_CODE_SELECT_CAR_BRAND:

                selectedCarBrand = (CarInfo.CarBrand) data.getSerializableExtra("data");
                if (null != selectedCarBrand) {

                    tvCarBrand.setText(selectedCarBrand.getTitle());
                }

                break;
            case REQUEST_CODE_SELECT_SHOP_PROPERTY:

                Bundle bundle = data.getBundleExtra("data");
                shopPropertyName = bundle.getString(Constants.SHOPE_PROPERTY_NAME, "");
                shopPropertyIndex = bundle.getInt(Constants.SHOP_PROPERTY_INDEX, 0);
                tvSjXz.setText(shopPropertyName);
                break;

            case ImageCaptureManager.REQUEST_TAKE_PHOTO:

                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();
                    localImgPath = captureManager.getCurrentPhotoPath();
                    ImageLoadUtil.loadImg(CreateNewOrganizeActivity.this, localImgPath, ivBusinessLicense);
                }
                break;

            default:
                break;
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_select_province:

                startActivityForResult(new Intent(this, AreaSelectActivity.class), REQUEST_CODE_SELECT_PROVINCE);
                break;
            case R.id.ll_city_select:

                if (null == selectedProvince) {
                    SToast.show("请选择省份");
                    return;
                }

                Intent intent = new Intent(this, AreaSelectActivity.class);
                intent.putExtra("PARENT_LEVEL_INFO", selectedProvince);
                startActivityForResult(intent, REQUEST_CODE_SELECT_CITY);

                break;
            case R.id.ll_zone_select:

                if (null == selectedCity) {
                    SToast.show("请选择城市");
                    return;
                }

                Intent intent2 = new Intent(this, AreaSelectActivity.class);
                intent2.putExtra("PARENT_LEVEL_INFO", selectedCity);
                startActivityForResult(intent2, REQUEST_CODE_SELECT_COUNTY);

                break;

            case R.id.ll_car_brand_select:

                Intent selectCarBrandAct = new Intent(this, SelectCarBrandActivity.class);
                selectCarBrandAct.putExtra("LIST_TYPE", 0);
                startActivityForResult(selectCarBrandAct, REQUEST_CODE_SELECT_CAR_BRAND);

                break;

            case R.id.ll_sjxz_select:
                Intent shopProperty = new Intent(this, SelectCarBrandActivity.class);
                shopProperty.putExtra("LIST_TYPE", 1);
                startActivityForResult(shopProperty, REQUEST_CODE_SELECT_SHOP_PROPERTY);
                break;

            case R.id.iv_business_license_photo_select:

                requestCameraAndAccessFiles();
                break;

            case R.id.iv_goto_top:
                svContent.smoothScrollTo(0, 0);
                break;

            case R.id.btn_require_submit:
                if (verifyInputValid())
                    uploadImgToOss(localImgPath);
                break;

            default:
                break;
        }
    }


    /**
     * 上传图片
     *
     * @param localImgPath
     */
    private void uploadImgToOss(String localImgPath) {

        if( !TextUtils.isEmpty(localImgPath) && !localImgPath.startsWith("http")){
            showDialog();
            MyApplication.getInstance().getOssService(this).asyncPutImage(OssService.getOssObjectInfo(false), localImgPath, null);
        }

    }

    private boolean verifyInputValid() {

        if (TextUtils.isEmpty(etCompanyFullName.getText().toString())) {
            SToast.show("请输入公司全称");
            return false;
        }
        if (TextUtils.isEmpty(etCompanyShortName.getText().toString())) {
            SToast.show("请输入公司简称");
            return false;
        }
        if (null == selectedProvince) {
            SToast.show("请选择省份");
            return false;
        }

        if (null == selectedCity) {
            SToast.show("请选择城市");
            return false;
        }
        if (null == selectedCounty) {
            SToast.show("请选择区域");
            return false;
        }
        if (TextUtils.isEmpty(etContacts.getText().toString())) {
            SToast.show("请输入联系人");
            return false;
        }
        if (TextUtils.isEmpty(etContactNumber.getText().toString())) {
            SToast.show("请输入联系电话");
            return false;
        }
        if (!PhoneUtil.isMobileNO(etContactNumber.getText().toString())) {
            SToast.show("联系电话格式有误");
            return false;
        }

        if (TextUtils.isEmpty(shopPropertyName)) {
            SToast.show("请选择商家性质");
            return false;
        }
        if (!cbYwMk.isChecked() && !cbJkMk.isChecked() && !cbCsMk.isChecked() && !cbFastEvaluate.isChecked()) {
            SToast.show("请选择模块");
            return false;
        }
        if (TextUtils.isEmpty(etBusinessLicenseCode.getText().toString())) {
            SToast.show("请输入营业执照号码");
            return false;
        }
        if (TextUtils.isEmpty(localImgPath)) {
            SToast.show("请上传营业执照照片");
            return false;
        }


        return true;

    }


    @Override
    public void onUploadOk(String imgUrl, Object tag) {
        dismissDialog();
        localImgPath = imgUrl;
        applyForChannel();
    }


    private void applyForChannel() {

        HashMap<String, String> params = new HashMap<>();
        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());

        params.put("title", etCompanyFullName.getText().toString());
        params.put("abname", etCompanyShortName.getText().toString());

        if(!TextUtils.isEmpty(etCarDealerCode.getText().toString())){

            params.put("cnkey", etCarDealerCode.getText().toString());
        }

        params.put("province", selectedProvince.getId() );
        params.put("city", selectedCity.getId());
        params.put("county", selectedCounty.getId());

        if(!TextUtils.isEmpty(etAddress.getText().toString())){
            params.put("address" , etAddress.getText().toString() );
        }

        params.put("realname", etContacts.getText().toString());
        params.put("mobile", etContactNumber.getText().toString());

        if( null != selectedCarBrand ){
            params.put("brand", selectedCarBrand.getId());
        }
        params.put("ctype", String.valueOf(shopPropertyIndex));

        params.put("Module", getApplyModuleIds());

        if(!TextUtils.isEmpty(etRecommendCode.getText().toString())){
            params.put("Salekey", etRecommendCode.getText().toString());
        }
        params.put("licid", etBusinessLicenseCode.getText().toString());

        params.put("licimg", localImgPath);

        for (String key : params.keySet()) {

            Log.e(TAG, "applyForChannel:  Key : " + key + " \t Value : " + params.get(key));
        }

        ApiClient.postForm(HttpConstants.APPLY_FOR_NEW_CHANNEL, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                Log.e(TAG, "onResponse: " + response);

                try {

                    JSONObject jsonObj = new JSONObject(response);

                    if (TextUtils.equals(jsonObj.optString("code", "0"), "1")) {
                        SToast.show("申请成功");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MyApplication.getInstance().removeActivity(CreateNewOrganizeActivity.class);
                                finish();
                            }
                        }, 1000);

                    } else {
                        SToast.show(jsonObj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //    获取已选中申请通道id，以，分隔
    private String getApplyModuleIds() {

        StringBuilder builder = new StringBuilder();

        if (cbYwMk.isChecked()) {
            builder.append("1");
        }
        if (cbJkMk.isChecked()) {
            if (builder.length() != 0)
                builder.append(",");
            builder.append("2");
        }
        if (cbCsMk.isChecked()) {
            if (builder.length() != 0)
                builder.append(",");
            builder.append("3");
        }
        if (cbFastEvaluate.isChecked()) {
            if (builder.length() != 0)
                builder.append(",");
            builder.append("4");
        }

        return builder.toString();

    }

    @AfterPermissionGranted(REQUEST_CAMERA_FILES_PERMISSIONS)
    public void requestCameraAndAccessFiles(){

        String[] perms = new String[]{Manifest.permission.CAMERA , Manifest.permission.READ_EXTERNAL_STORAGE };

        if(EasyPermissions.hasPermissions(this,perms)){
            showImgSelectDialog("营业执照");
        }else{
            EasyPermissions.requestPermissions(this,"请授予必要权限！",REQUEST_CAMERA_FILES_PERMISSIONS,perms);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode , permissions,grantResults,this);
    }

    @Override
    public void onUploadFailed() {
        dismissDialog();
        SToast.show("图片上传失败");
    }

    public void showImgSelectDialog(String titleStr ){

        if( null == imgSelectDialog ){
            imgSelectDialog = new ImageSelectDialog(this , this , titleStr );
        }else{
            imgSelectDialog.setTitleStr(titleStr);
        }
        imgSelectDialog.show();

    }


    @Override
    public void onTakePhotoWithSystemCamera() {

        openSystemCamera();

    }

    private void openSystemCamera() {
        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSelectImgOnGallery() {

        pickPhoto();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.e(TAG, "requestCameraAndAccessFiles: onPermissionsGranted =================  " );
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        if(EasyPermissions.somePermissionPermanentlyDenied(this,perms)){
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
